<?php

/**
 * 默认控制器
 */
class Controller_Default extends Controller_Abstract
{
    function __construct($app)
    {
        parent::__construct($app);
        $this->_app = $app;
        $this->_view['store']=$this->store=Q::INI('store');
        $this->_view['roles']=$this->_app->currentUserRoles();
        if(in_array('customer',$this->_view['roles'])){
            $c=$this->_app->currentUser();
            $this->_view['customer']=$this->customer=$c['customer'];
        }
        if(empty($this->store)){
            return $this->_404();
        }
        // language 在解晰 url 时 已经 被 设置 
        if(isset($_REQUEST['language'])&&strlen($_REQUEST['language'])){
            $language=$_REQUEST['language'];
            if($language!=Q::ini('language')){
                $sl=Store_Language::find('store_id=? And language=?',Q::ini('store/store_id'),$language)->getOne();
                if(!$sl->isNewRecord()){
                    Q::replaceIni('language',$language);
                }
            }
        }
        if(strlen(Q::ini('language'))<=0){
            Q::replaceIni('language',Q::INI('store/language'));
        }
        //change currency
        // 这里可能.并不需要 把货币放在 Cart 中 
        if($this->_context->query('currency')){
            Helper_Currency::set($this->_context->query('currency'));
//             Helper_Cart::cart('currency',$this->_context->query('currency'));
        }
    }

    function actionIndex()
    {
        $this->_view['goods_hot']=Goods::find('[store_id]=? And [tags.tag_name]=?',$this->store['store_id'],'hot')
                ->group('[goods_id]')->order('updated DESC')->limit(0,4)->getAll();
        $this->_view['goods_special']=Goods::find('[store_id]=? And [tags.tag_name]=?',$this->store['store_id'],'special')
                ->group('[goods_id]')->order('updated DESC')->limit(0,4)->getAll();
        $this->_view['goods_news']=Goods::find('store_id=?',$this->store['store_id'])
            ->order('created DESC')->limit(0,4)->getAll();
        
        //  自 定义   Define_Default_Index_Main.html
    }
    
    function actionList(){
        $group=false;
        $category_id=$this->_context->query('category_id');
        $tag_id=$this->_context->query('tag_id');
        $search_key=trim($this->_context->query('search_key'));
        $tag=$this->_context->query('tag');
        
        $this->_view['url_args']=array();
        
        $gs=Goods::find('[store_id]=?',$this->store['store_id']);
        if(strlen($category_id)){
            $path=Category::path($this->store['store_id'],$category_id);
            if(count($path)){ foreach($path as $n){
                $this->_view['navigation'][]=array('title'=>$n->name,'url'=>_url('list',array('category_id'=>$n->category_id)));
            }}
            $this->_view['url_args']['category_id']=$category_id;
            $ca=Helper_Array::getCols(Category::children($this->store['store_id'],$category_id)->toArray(),'category_id');
            $ca[]=$category_id;
            $gs->where('[category_id] in(?)',$ca);
        }
        
        if(strlen($tag_id)){
            $tag=Taggoods::find('tag_id=?',$tag_id)->getOne();
            $this->_view['navigation'][]=array('title'=>$tag->tag_name,'url'=>_url('list',array('tag'=>$tag->tag_name)));
            $this->_view['url_args']['tag']=$tag->tag_name;
            $gs->where('[tags.tag_id]=?',$tag_id);
            $group=1;
        }else if(strlen($tag)){
            $ttag=Taggoods::find('store_id=? And  tag_name like ?',$this->store['store_id'],$tag)->getOne();
            if(!$ttag->isNewRecord()){
                $this->_view['navigation'][]=array('title'=>$tag,'url'=>_url('list',array('tag'=>$tag)));
                $this->_view['url_args']['tag']=$tag;
                $gs->where('[tags.tag_id] like ?',$ttag->tag_id);
                $group=1;
            }
        }
        
        if(strlen($search_key)){
            $this->_view['navigation'][]=array('title'=>'Products','url'=>_url('list'));
            $gs->where('[langdesc.title] like ?','%'.$search_key.'%');
        }
        if($group){
            $gs->group('[goods_id]');
        }
        $gs->limitPage($this->_context->query('page', 0), 15);
        $gs->fetchPagination($this->_view['pager']);
        $this->_view['goods'] =$gs->getAll();
        
    }
    
    function actionProduct(){
        if($this->_context->query('product_id')){
            $goods_id=$this->_context->query('product_id');
        }elseif($this->_context->query('goods_id')){
            $goods_id=$this->_context->query('goods_id');
        }elseif($this->_context->query('id')){
            $goods_id=$this->_context->query('id');
        }
        $g=Goods::find('store_id=?',$this->store['store_id']);
        $g->where('goods_id=?',$goods_id);
        $this->_view['g']=$g->getOne();
        $path=Category::path($this->store['store_id'],$this->_view['g']->category_id);
        if(count($path)) foreach($path as $n){
            $this->_view['navigation'][]=array('title'=>$n->name,'url'=>_url('list',array('category_id'=>$n->category_id)));
        }
        
    }
    
    function actionBuy(){
        
    }
    /***
     *   订单信息  
     **/
    function actionOrder(){
        if($this->_context->query('order_id')){
            $this->_view['order']=Orders::find('store_id=? And order_id=?',$this->store['store_id'],$this->_context->query('order_id'))->getOne();
        }
        if(isset($this->_view['order'])&&!$this->_view['order']->isNewRecord()){
            $this->_view['shipment']=Store_Shipment::find('id=?',$this->_view['order']['shipment_id'])->getOne();
            $this->_view['payment']=Payment::find('payment_id=?',$this->_view['order']['payment_id'])->getOne();
            $this->_view['transactions']=Transaction::find('order_id=?',$this->_context->query('order_id'))->getAll();
            $this->_view['order_id']=$this->_context->query('order_id');
        }else{
            $this->_view['error']['exist']=1;
        }
//         Helper_cart::cart('status',3);
    }
    
    /****
     * 接收 付款 操作 页面 .
     */         
    function actionToPay(){
        $order_id=$this->_context->post('order_id');
        $amount=$this->_context->post('amount');
        $currency=$this->_context->post('currency');
        $payment_id=$this->_context->post('payment');
        $item_name=$this->_context->post('item_name');
        if($order_id &&$amount&&$currency&&$payment_id){
//             $ts=Transaction::find('order_id=? And status_payment=?',$this->_context->query('order_id'),'wait')->getAll();
//             if(count($ts)){
//                 
//             }
            $mypayment=Store_Payment::find('store_id=? And payment_id=?',$this->store['store_id'],$payment_id)->getOne();
            switch($mypayment->payment->code){
                case 'paypal':
                    $is_sanbox=$mypayment->status&2; //是否是 sandbox .
                    $config=$mypayment->config;
                    $parameter=array(
        				"amount"=>$amount,
        				"currency_code"=>$currency,
        				"item_name"=>$item_name , //显示给客户的标题
        				"item_number"=>$order_id.'-'.$this->store['store_id'], //我想这里不必要用 md5 加密
        				"invoice"=>$order_id.'-'.$this->store['store_id'].'-cms',
        				'return'=>'http://'.$this->store['domain']._url('order',array('order_id'=>$order_id)),
        				'url_cancel_return'=>'http://'.$this->store['domain']._url('order',array('order_id'=>$order_id)),
        				'notify_url'=>'http://'.$this->store['domain'].url('service/Paypalnotify')
        			);
                    if(isset($config['business'])){
                        $parameter['business']=$config['business'];
                    }
                    if(empty($parameter['item_name'])){
                        $parameter['item_name']=$parameter['item_number'];
                    }
        			$paypal=new Helper_Pay_paypal();
        			$url=$paypal->getRequestUrl($parameter,$is_sanbox);
                	return $this->_redirect($url);
    			break;
    			default:
    			    $this->_view['error']['nopayment']=1;
    			break;
    		}
        }else{
            $this->_view['error']['inputfalse']=1;
        }
        $this->_view['error']['other']=2;
    }
    /***
     * SESSION 中的 订单 列表 
     */
    function actionTmpOrderList(){
        //本次购买的记录 :
        if(Helper_Cart::ordercount()){
            $oid=Helper_Cart::orders();
            if(count($oid)){
                if($this->_context->isPost()){
                    $pos=$this->_context->post('order_id');
                    switch($this->_context->post('aktion')){
                        case 'remove': ///从 cookie 中删除 
                        if(count($pos)) foreach($pos as $o){
                            Helper_Cart::orderAdd($o,'remove');
                        }
                        break;
                    }
                    return $this->_redirect(_url('tmporderlist'));
                }else{
                    $this->_view['orders']=Orders::find('store_id=? And order_id in(?)',$this->store['store_id'],$oid)
                        ->order('created DESC')->getAll();
                }
            }
        }
    }
    
    // 添加 
    function actionCartAdd(){
        $sg=Helper_cart::cart('goods');
        $qs=$this->_context->post('quantity');
        $ps=$this->_context->post('props');
        $propstr= Helper_Cart::propstr($ps);
        if(is_array($qs)&&count($qs)){
            $mgs=Goods::find('goods_id in (?)',array_keys($qs))->getAll();
            foreach($mgs as $g){
                $q=(int)$qs[$g->goods_id];
                if(isset($sg[$g->goods_id.$propstr])){
                    $sg[$g->goods_id.$propstr]['quantity']+=$q;
                }else{
                    $propstr2=Helper_Cart::propstr($ps,0);
                    if(strlen($propstr2)>0) $propstr2='('.$propstr2.')';
                    $sg[$g->goods_id.$propstr]=array(
                        'goods_id'=>$g->goods_id,
                        'props'=>$ps,
                        'quantity'=>$q,
                        'weight'=>$g->weight,
                        'price'=>$g->price,
                        'title'=>($g->title).$propstr2,
                        'currency'=>$g->currency,
                    );
                }
            }
            Helper_cart::cart('goods',$sg);
            Helper_cart::recalculate();
            Helper_cart::cart('status',1);
        }
        return $this->_redirect(_url('cart')); 
    }
    /** 
     * List
     */    
    function actionCart()
    {
        if(Helper_cart::cart('status')<=0){
            ' No products';
        }
        $sg=Helper_cart::cart('goods');
        //更新数量
        if($this->_context->isPost() && count($this->_context->post('quantity'))){
            $qs=$this->_context->post('quantity');
            foreach($qs as $k=>$q){
                $q=(int)$q;
                if($q<=0&&isset($sg[$k])){
                    unset($sg[$k]);
                }else{
                    $sg[$k]['quantity']=$q;
                }
            }
            Helper_cart::cart('goods',$sg);
            
            // 货币
            if(strlen($this->_context->post('currency'))){
                Helper_cart::cart('currency',$this->_context->post('currency'));
            }
            Helper_cart::recalculate();
            Helper_cart::cart('status',1);
            if(isset($this->customer)){
                return $this->_redirect(_url('checkout'));
            }else{
                return $this->_redirect(_url('cartlogin'));
            }
        }
        if(count($sg)){
            $this->_view['goods']=Helper_Array::toHashmap(Goods::find('goods_id in (?)',Helper_Array::getCols($sg,'goods_id'))->getAll()->toArray(),'goods_id');
        }
        $this->_view['cart']=Helper_cart::cart();
    }
    
    function actionCartRemoveGood(){
        $cartkey=$this->_context->query('cartkey');
        $sg=Helper_cart::cart('goods');
        unset($sg[$cartkey]);
        Helper_cart::cart('goods',$sg);
        Helper_cart::recalculate();
        return $this->_redirect(_url('cart'));
    }
    function actionCartlogin(){
        
    }
    /****
     * 
     */
    function actionCheckout(){
        $this->_view['cart']=Helper_cart::cart();
        if(isset($this->customer)&&
            (empty($this->_view['cart']['ship']['customer_id'])||$this->_view['cart']['ship']['customer_id']!=$this->customer['customer_id'])
            ){
            $this->_view['cart']['ship']=$this->customer;
        }
        if(!isset($this->_view['cart']['ship'])){
            $this->_view['cart']['ship']=Helper_cart::$ship;
        }
        if($this->_context->isPost()){
            $ship=array_merge($this->_view['cart']['ship'],$_POST);
            // 收件人 ship 
            if(strlen($ship['email'])
                &&strlen($ship['firstname'])
                &&strlen($ship['lastname'])
                &&strlen($ship['street1'])
                &&strlen($ship['phone'])
                &&strlen($ship['postalcode'])
                &&strlen($ship['country'])
            ){
                Helper_cart::cart('ship',$ship);
                if(isset($this->customer)){
                    Helper_cart::cart('customer_id',$this->customer['customer_id']);
                }
            }else{
                $this->_view['error']['ship']=1;
            }
            // 货币
            if(strlen($this->_context->post('currency'))){
                Helper_cart::cart('currency',$this->_context->post('currency'));
            }
            // 配送方式
            if(strlen($this->_context->post('shipment'))){
                Helper_cart::cart('shipment',$this->_context->post('shipment'));
            }else{
                $this->_view['error']['shipment']=1;
            }
            // 支付方式
            if(strlen($this->_context->post('payment'))){
                Helper_cart::cart('payment',$this->_context->post('payment'));
            }else{
                $this->_view['error']['payment']=1;
            }
            if($this->_view['cart']['amount']>0){
                
            }else{
                $this->_view['error']['goods']=1;
            }
            // 附加 order 字段
            $order_fields_array=array(
                'memo'=>$this->_context->post('memo')
            );
            
            if(!isset($this->_view['error'])){
                $order=Helper_cart::buildOrder($order_fields_array);
                if($order){
                    Helper_cart::destroy();
                    Helper_mail::sendOrdercreated($order);
                    return $this->_redirect(_url('order',array('order_id'=>$order->order_id)));
                }
            }
        }
        
        $this->_view['country_array']=Helper_Array::toHashmap(Country::find('')->getAll()->toArray(),'country','description');
        $this->_view['shipments']=Store_Shipment::find('store_id=? And status&1',$this->store['store_id'])->getAll();
        $this->_view['payments']=Store_Payment::find('store_id=?',$this->store['store_id'])->getAll();
        if(count($this->_view['cart']['goods'])){
            $this->_view['goods']=Helper_Array::toHashmap(Goods::find('goods_id in (?)',Helper_Array::getCols($this->_view['cart']['goods'],'goods_id'))->getAll()->toArray(),'goods_id');
        }
    }
    
    function actionCartDestroy(){
        Helper_cart::destroy();
        return $this->_redirect(_url('cart'));
    }
    
    /**
     * All Them Can 
     */         
    function actionCartCoupon(){
        if(Helper_cart::coupon(trim($this->_context->post('coupon')))){
            //return $this
        }else{
            
        }
        return $this->_redirect(_url('cart'));
    }
    
    /**
     * 物流费  计费    
     * 接收国家
     * 用 shopping cart 中的商品   
     * 用 shippingment 中 的所有 物流 项 
     */    
    function actionAjaxShippingfeecalculater(){
        $str=Helper_Cart::shipcost_calculate($this->_context->post('country'));
        echo json_encode($str);
        die();
    }
    
    function actionLogin(){
        if(isset($this->customer)){
            if(strlen($this->_context->r)){
                return $this->_redirect(urldecode($this->_context->r));
            }else{
                return $this->_redirect(_url('userInfo'));
            }
        }
        $this->_view['u']=array(
            'email'=>$this->_context->post('email'),
            'firstname'=>$this->_context->post('firstname'),
            'lastname'=>$this->_context->post('lastname'),
            'gender'=>$this->_context->post('gender'),
            'company'=>$this->_context->post('company'),
            'street1'=>$this->_context->post('street1'),
            'street2'=>$this->_context->post('street2'),
            'cityname'=>$this->_context->post('cityname'),
            'stateorprovince'=>$this->_context->post('stateorprovince'),
            'country'=>$this->_context->post('country'),
            'phone'=>$this->_context->post('phone'),
            'postalcode'=>$this->_context->post('postalcode'),
        );
        if($this->_context->isPost()){
        do{
            if($this->_context->cmd=='login'){
                
                 $u=Customers::find('[email]=? And [store.store_id]=?',$_POST["email"],$this->store['store_id'])->query();
          	     if($u->isNewRecord()){
          	         $this->_view['error']['lemail']=1;
                     break;
                 }
                 if($u->password!=md5($_POST["password"])){
                     $this->_view['error']['lpassword']=1;
                     break;
                 }
    			 $this->_app->changeCurrentUser(array('customer'=>$u->toArray()),"customer");
    			if(strlen($this->_context->r)){
                    return $this->_redirect(urldecode($this->_context->r));
                }else{
                    return $this->_redirect(_url("index"));
                }
            }elseif($this->_context->cmd=='signup'){
                // 收件人 ship 
                if(!(strlen($this->_context->post('email'))
                    &&strlen($this->_context->post('firstname'))
                    &&strlen($this->_context->post('lastname'))
                    &&strlen($this->_context->post('password'))
                    &&strlen($this->_context->post('password2'))
                )){
                    $this->_view['error']['signup']=1;
                    break;
                }
                
                if($this->_context->post('password')!=$this->_context->post('password2')){
                    $this->_view['error']['password2']=1;
                    break ;
                }
                if(strlen($this->_context->post('password'))<=5){
                    $this->_view['error']['password']=1;
                    break ;
                }
                
                $n=Customers::find('[email]=? And [store.store_id]=?',$_POST["email"],$this->store['store_id'])->query();
                if(!$n->isNewRecord()){
                    $this->_view['error']['exist']=1;
                    break;
                }
                $this->_view['u']['password']=md5($this->_context->post('password'));
                $n->changeProps($this->_view['u']);
                $n->store_id=$this->store['store_id'];
                $n->save();
                if($n->id()){
                    $this->_app->changeCurrentUser(array('customer'=>$n->toArray()),"customer");
        		    Helper_Mail::sendRegister($n); // send mail
                    if(strlen($this->_context->r)){
                        return $this->_redirect(urldecode($this->_context->r));
                    }else{
                        return $this->_redirect(_url("index"));
                    }
                }else{
                    $this->_view['error']['other']=1;
                    break;
                }
            }
        }while(0);
        }
        $this->_view['country_array']=Helper_Array::toHashmap(Country::find('')->getAll()->toArray(),'country','description');
    }
    
    //注销
    function actionLogout(){
        Helper_Cart::cart('customer_id',0);
        $this->_app->cleanCurrentUser();
        return $this->_redirect(_url("index"));
    }
    
    
    function actionUserInfo(){
        if(!isset($this->customer)){return $this->_redirect(_url("login"));}
    }
    
    function actionUserOrders(){
        if(!isset($this->customer)){return $this->_redirect(_url("login"));}
        $select=Orders::find('customer_id=? And store_id=?',$this->customer['customer_id'],$this->store['store_id']);
        $select->limitPage($this->_context->query('page', 0), 15);
        $select->fetchPagination($this->_view['pager']);
        $this->_view['orders'] =$select->order('created DESC')->getAll();
        
        $this->_view['url_args']=array('name'=>$this->_context->query('name'));
    }
    
    function actionUserInfoEdit(){
        if(!isset($this->customer)){return $this->_redirect(_url("login"));}
        $u=Customers::find('[customer_id]=? And [store.store_id]=?',$this->_view['customer']['customer_id'],$this->store['store_id'])->query();
        $this->_view['u']=$u;
        $n=array(
            'firstname'=>$this->_context->post('firstname'),
            'lastname'=>$this->_context->post('lastname'),
            'gender'=>$this->_context->post('gender'),
            'company'=>$this->_context->post('company'),
            'street1'=>$this->_context->post('street1'),
            'street2'=>$this->_context->post('street2'),
            'cityname'=>$this->_context->post('cityname'),
            'stateorprovince'=>$this->_context->post('stateorprovince'),
            'country'=>$this->_context->post('country'),
            'phone'=>$this->_context->post('phone'),
            'postalcode'=>$this->_context->post('postalcode'),
        );
        $this->_view['country_array']=Helper_Array::toHashmap(Country::find('')->getAll()->toArray(),'country','description');
        if(strlen($n['country'])&&isset($this->_view['country_array'][$n['country']])){
            $n['countryname']=$this->_view['country_array'][$n['country']];
        }
        if($this->_context->isPost()){
        do{
            // 收件人 ship 
            if(!(strlen($this->_context->post('firstname'))
                &&strlen($this->_context->post('lastname'))
            )){
                $this->_view['error']['other']=1;
                break;
            }

            $u->changeProps($n);
            $u->save();
            //重写  用户信息 
            $this->_app->changeCurrentUser(array('customer'=>$u->toArray()),"customer");
            $this->_view['error']['success']=1;
        }while(0);
        $this->_view['u']=$n;
        }
    }
    
    function actionUserPassword(){
        if(!isset($this->customer)){return $this->_redirect(_url("login"));}
        if ($this->_context->isPOST()){
           do{
                if($this->_context->post('newpassword')!=$this->_context->post('newpassword2')){
                    $this->_view['error']['newpassword2']=1;
                    break ;
                }
                if(strlen($this->_context->post('newpassword'))<=5){
                    $this->_view['error']['newpassword']=1;
                    break ;
                }
                $u=Customers::find('[customer_id]=? And [store.store_id]=?',$this->_view['customer']['customer_id'],$this->store['store_id'])->query();
                if($seller->password!=md5($this->_context->post('oldpassword'))){
                   $this->_view['error']['oldpassword']=1;
                   break ;
                }
                $u->password=md5($this->_context->post('newpassword'));
                $u->save();
                $this->_view['error']['success']=1;
            }while(0);
        }
    }
}

/***
 * $udi 用 action 来 代 了 
 *  把语言 写入 url 中  
 */ 
function _url($udi='index', $params = null, $route_name = 'language', array $opts = null){
    if(is_array($udi)){
        if(!isset($udi['controller'])){
            $udi['controller']='default';
        }
    }else{
        $udi=array(
          'controller'=>'default',
          'action'=>$udi,
//           'language'=>$language
        );
    }
//         if(!isset($udi['language'])&&Q::ini('language')!=Q::ini('store/language')){
//             $udi['language']=Q::ini('language').'_'.Q::ini('store/language');
//         }
    if(!isset($udi['language'])){
        $udi['language']=Q::ini('language');
    }
    return url($udi,$params,$route_name,$opts);
}